using System.Text;
using B.S.ReportEvent.Api.Utils;
using B.S.ReportEvent.ApiNew.Utils;
using B.S.ReportEvent.Infrastructure.Implements;
using B.S.ReportEvent.Infrastructure.Interfaces;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

namespace B.S.ReportEvent.ApiNew.Extensions;

/// <summary>
/// 服务拓展类
/// </summary>
public static class ServiceCollectionExtensions
{
    /// <summary>
    /// 注册数据库
    /// </summary>
    /// <typeparam name="TDbContext"></typeparam>
    /// <param name="services"></param>
    /// <param name="connectionString"></param>
    /// <param name="enableSqlLog"></param>
    /// <returns></returns>
    public static IServiceCollection AddDbContextService<TDbContext>(this IServiceCollection services, string? connectionString, bool enableSqlLog) where TDbContext : DbContext
    {
        return services.AddDbContext<TDbContext>(builder =>
        {
            //用到事务需要把重试策略删掉
            builder.UseSqlServer(connectionString!).EnableSensitiveDataLogging();

            if (enableSqlLog)
                builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                {
                    configure
                        .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        .AddConsole();
                }));
        });
    }

    /// <summary>
    /// 注册JWT
    /// </summary>
    /// <param name="collection"></param>
    /// <param name="builder"></param>
    public static void AddJwt(this IServiceCollection collection, WebApplicationBuilder builder)
    {
        builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                //取出私钥
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],
                    //验证接收者
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["Authentication:Audience"],
                    //验证是否过期
                    ValidateLifetime = true,
                    //验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                };
            });
    }

    /// <summary>
    /// 注入服务的拓展类
    /// </summary>
    /// <param name="services"></param>
    /// <returns></returns>
    public static IServiceCollection AddServices(this IServiceCollection services)
    {
        services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>)); //注入仓储

        //注入仓储
        services.AddScoped<IWfInstancesRepository, WfInstancesRepository>();
        services.AddScoped<IProcessRecordsRepository, ProcessRecordsRepository>();
        services.AddScoped<IHttpHelper, HttpHelper>();

        //注入AutoMapper
        services.AddAutoMapper(typeof(MappingProfile));

        //注入全局异常处理
        services.AddControllers(x => x.Filters.Add<GlobalExceptionFilter>());

        return services;
    }
}